package com.intelligent.health.base.service.email.impl;

import com.intelligent.health.base.excption.EmailSendException;
import com.intelligent.health.base.service.email.SendEmailService;
import entity.EmailInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/04/05/10:00
 * @Description: 邮件发送服务
 */
@Component
public class SendEmailServiceImpl implements SendEmailService {

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    TemplateEngine templateEngine;

    /**
     * 简单邮件
     */
    private final String SIMPLE_MAIL = "SIMPLE_MAIL";

    /**
     * 带附件邮件
     */
    private final String ATTACHFILE_MAIL = "ATTACHFILE_MAIL";

    /**
     * 带图片邮件
     */
    private final String IMGRES_MAIL = "IMGRES_MAIL";

    /**
     * 模板引擎邮件
     */
    private final String THYMELEAF_MAIL = "THYMELEAF_MAIL";

    @Override
    public void emailSend(String action, EmailInfo emailInfo) throws EmailSendException, MessagingException {
        switch (action) {
            case SIMPLE_MAIL:
                sendSimpleMail(emailInfo);
                break;
            case ATTACHFILE_MAIL:
                sendAttachFileMail(emailInfo);
                break;
            case IMGRES_MAIL:
                sendImgResMail(emailInfo);
                break;
            case THYMELEAF_MAIL:
                sendThymeleafMail(emailInfo);
                break;
            default:
                throw new EmailSendException("传入action参数有误");
        }
    }

    /**
     * 普通邮件发送
     *
     * @param emailInfo 邮件信息
     */
    public void sendSimpleMail(EmailInfo emailInfo) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject(emailInfo.getSubJect());
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom(emailInfo.getFromEmail());
        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        // message.setTo("10*****16@qq.com","12****32*qq.com");
        message.setTo(emailInfo.getToEmail());
        // 设置邮件抄送人，可以有多个抄送人
        message.setCc(emailInfo.getCcEmail());
        // 设置隐秘抄送人，可以有多个
        message.setBcc(emailInfo.getBccEmail());
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText(emailInfo.getText());
        // 发送邮件
        javaMailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     *
     * @param emailInfo 邮件信息
     * @throws MessagingException 异常
     */
    public void sendAttachFileMail(EmailInfo emailInfo) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setSubject(emailInfo.getSubJect());
        helper.setFrom(emailInfo.getFromEmail());
        helper.setTo(emailInfo.getToEmail());
        helper.setCc(emailInfo.getCcEmail());
        helper.setBcc(emailInfo.getBccEmail());
        helper.setSentDate(new Date());
        helper.setText(emailInfo.getText());
        // 第一个参数是自定义的名称，后缀需要加上，第二个参数是文件的位置
        if (emailInfo.getHashMap() != null) {
            for (Map.Entry<String, String> entry : emailInfo.getHashMap().entrySet()) {
                helper.addAttachment(entry.getKey(), new File(entry.getValue()));
            }
        }
        javaMailSender.send(mimeMessage);
    }

    /**
     * 正文中带图片的邮件
     *
     * @param emailInfo 邮件信息
     * @throws MessagingException 异常
     */
    public void sendImgResMail(EmailInfo emailInfo) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject(emailInfo.getFromEmail());
        helper.setFrom(emailInfo.getFromEmail());
        helper.setTo(emailInfo.getToEmail());
        helper.setCc(emailInfo.getCcEmail());
        helper.setBcc(emailInfo.getCcEmail());
        helper.setSentDate(new Date());
        // src='cid:p01' 占位符写法 ，第二个参数true表示这是一个html文本
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<p>hello 大家好，这是一封测试邮件，这封邮件包含图片，分别如下</p>");
        int count = 1;
        for (Map.Entry<String, String> entry : emailInfo.getHashMap().entrySet()) {
            stringBuilder.append("</p><img src='cid:p");
            stringBuilder.append(count++);
            stringBuilder.append("'/><p>");
        }
        helper.setText(String.valueOf(stringBuilder), true);
        count = 1;
        // 第一个参数指的是html中占位符的名字，第二个参数就是文件的位置
        for (Map.Entry<String, String> stringStringEntry : emailInfo.getHashMap().entrySet()) {
            helper.addInline("p" + count++, new FileSystemResource(new File(stringStringEntry.getValue())));
        }
        javaMailSender.send(mimeMessage);
    }


    /**
     * 使用 Thymeleaf 作邮件模板
     *
     * @param emailInfo 邮件信息
     * @throws MessagingException 异常
     */
    public void sendThymeleafMail(EmailInfo emailInfo) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject(emailInfo.getSubJect());
        helper.setFrom(emailInfo.getFromEmail());
        helper.setTo(emailInfo.getToEmail());
        helper.setCc(emailInfo.getCcEmail());
        helper.setBcc(emailInfo.getBccEmail());
        helper.setSentDate(new Date());
        // 这里引入的是Template的Context
        Context context = new Context();
        // 设置模板中的变量
        context.setVariable("username", "javaboy");
        context.setVariable("num", "000001");
        context.setVariable("salary", "99999");
        // 第一个参数为模板的名称
        String process = templateEngine.process("email-template.html", context);
        // 第二个参数true表示这是一个html文本
        helper.setText(process, true);
        javaMailSender.send(mimeMessage);
    }
}
